//
//  LiveTableViewController.m
//  MoreFunTV
//
//  Created by admin on 14-10-23.
//  Copyright (c) 2014年 admin. All rights reserved.
//

#import "LiveTableViewController.h"
#import "AppDelegate.h"
#import <Matchstick/Flint.h>
#import "static.h"
#import "lib/include/libanalysis/libanalysis.h"
#import "UIImageView+AFNetworking.h"

libanalysis *libaUrl = [[libanalysis alloc]init];
@interface LiveTableViewController ()
{
    int lastKnownPlaybackTime;
    __weak MatchstickDeviceController *_matchstickController;
}
@property MPMoviePlayerController *moviePlayer;
@end

@implementation LiveTableViewController

- (id)initWithClassInfo:(VideoInfo *)classInfo;
{
    self = [super init];
    if (self) {
        self.classInfo = classInfo;
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    AppDelegate *delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
    _matchstickController = delegate.matchstickDeviceController;
    //投射图标判断
    if (_matchstickController.deviceScanner.devices.count > 0) {
        self.navigationItem.rightBarButtonItem = _matchstickController.matchstickBarButton;
    }
    
    self.navigationItem.titleView = nil;
    UIButton *btnBack = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 44)];
    [btnBack setTitle:[NSString stringWithFormat:@"    %@",self.classInfo.strCategoryName] forState:UIControlStateNormal];
    btnBack.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btnBack.titleLabel.font = [UIFont boldSystemFontOfSize:19.0f];
    [btnBack setBackgroundColor:[UIColor clearColor]];
    [btnBack setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(clickRetun) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"return.png"]];
    image.frame = CGRectMake(0, 12, 10, 20);
    [btnBack addSubview:image];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    _cusAlterView = [[AlertCustomView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _cusAlterView.delegate = self;
    _cusAlterView.backgroundColor = [UIColor colorWithWhite:0.098 alpha:0.600];
    _cusAlterView.alpha = 0;
    [app.window addSubview:_cusAlterView];
    
    //频道选择
    [self addChannel];
    
    //直播信息列表
    [self addVideoLive];
    
    //集成刷新控件
    [self setupRefresh];
    
    _arrLive = [[NSMutableArray alloc]init];
    //请求直播数据
    [self requestLiveInfo];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _matchstickController.delegate = self;
}

- (void)shouldDisplayModalDeviceController {
    //投射按钮调用的方法
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myDevice" object:nil userInfo:nil];
}

- (void)didDiscoverDeviceOnNetwork {
    // Add the Matchstick icon if not present.
    self.navigationItem.rightBarButtonItem = _matchstickController.matchstickBarButton;
}

//请求直播数据
-(void)requestLiveInfo
{
    _rep = [[RequestParameter alloc]init];
    _rep.portID = 1;
    _rep.strCategoryID = self.classInfo.strCategoryId;
    _rep.strAreaID = @"";
    _rep.strStyleID = @"166";//卫视  167地方台
    _rep.strPageNo = @"1";
    _rep.strPageSize = @"30";
    _rep.flagPage = 100;
    
    [Loading showLoadingWithView:self.view];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//执行耗时操作
        
        SetUpSingleton *setUp = [SetUpSingleton sharedSetUp];
        if (setUp.firstWeiShiID == YES) {//如果当天第一次进入直接更新
            [NetWorkingHelper getLiveInfoWithRequestParameter:_rep];
            _rep.flagPage = 10000;
            for (int i = 0; i < setUp.pageWeiShiNumber; i++) {
                _rep.portID = 1;
                _rep.flag = ++_rep.flag;
                _rep.strPageNo = [NSString stringWithFormat:@"%d",i+1];
                //请求直播台的id信息 并存入数据库
                _arrId = [NetWorkingHelper getLiveInfoWithRequestParameter:_rep];
                setUp.firstWeiShiID = NO;
            }
        }
        
        //后面进入时查询数据库
        _rep.flag = 1;
        _arrId = [DBDaoHelper selectLiveID:_rep.flag];
        if (setUp.firstWeiShiEpg == YES) {//如果第一次进入直接更新Epg
            [DBDaoHelper deleteAllEPG];//删除所有EPG信息
            //获取详细的EPG信息 并存入数据库
            [NetWorkingHelper getDetailEPGInfoWith:_rep ArrLive:_arrId];
            setUp.firstWeiShiEpg = NO;
        }
        _rep.strPageNo = @"1";
        
        //从数据库请求数据
        [self selectDBDAO:_arrId.count];
        dispatch_async(dispatch_get_main_queue(), ^{
            //主线程更新UI
            [Loading hiddonLoadingWithView:self.view];
            [_tableLive reloadData];
        });
    });
}

//从数据库请求数据
-(void)selectDBDAO:(int)count
{
    //获取当前的时间戳／WithTimeIntervalSinceNow:-8*60*60
    NSDate *datenow = [[NSDate alloc]init];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    //查询当前的播放信息
    NSMutableArray  *arrNow = [[NSMutableArray alloc]init];
    for (int i = 0; i < count;i++ ) {
        LiveInfo *liveNow = [_arrId objectAtIndex:i];
        liveNow.strLiveTime = [NSString stringWithFormat:@"%@000",timeSp];
        LiveInfo *liveEpg = [DBDaoHelper selectNowEpgInfo:liveNow];
        liveNow.strTitle = liveEpg.strResTitle;
        liveNow.strId = liveEpg.strId;
        [arrNow addObject:liveNow];
    }
    
    //查询即将播放的视频信息
    for (int i = 0; i < arrNow.count;i++ ) {
        //部分EPG信息的对象
        LiveInfo *liveIn = [arrNow objectAtIndex:i];
        liveIn.strNextId = [NSString stringWithFormat:@"%d",[liveIn.strId intValue]+1];
        //包含所有epg信息的对象
        LiveInfo *liveEPG = [DBDaoHelper selectAllEpgInfo:liveIn];
        liveIn.strNextTitle = liveEPG.strNextTitle;
        [_arrLive addObject:liveIn];
    }
}

//频道选择
-(void)addChannel
{
    //底部的view
    UIView *chooseBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, 50)];
    chooseBgView.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000];
    [self.view addSubview:chooseBgView];
    
    for (int i = 0; i < 2; i++)
    {
        UIButton *btnChoose = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btnChoose.frame = CGRectMake(kScreenWidth/4*i, 0, kScreenWidth/4, 50);
        btnChoose.titleLabel.font = [UIFont systemFontOfSize:18.0f];
        [btnChoose setBackgroundColor:[UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000]];
        [btnChoose setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        if (i == 0)
        {
            [btnChoose setTitle:MyLocalizedString(@"mychoose1") forState:UIControlStateNormal];
        }
        else if (i == 1)
        {
            [btnChoose setTitle:MyLocalizedString(@"mychoose2") forState:UIControlStateNormal];
        }
        btnChoose.tag = 20 + i;
        [btnChoose addTarget:self action:@selector(clickChoose:) forControlEvents:UIControlEventTouchUpInside];
        [chooseBgView addSubview:btnChoose];
    }
    
    //底部的下划线
    UIView *viewL = [[UIView alloc]initWithFrame:CGRectMake(0, 49, kScreenWidth, 1)];
    viewL.backgroundColor = [UIColor colorWithWhite:0.784 alpha:1.000];
    [chooseBgView addSubview:viewL];
    
    _viewB = [[UIView alloc]initWithFrame:CGRectMake(15, 47, 50, 3)];
    _viewB.backgroundColor = [UIColor colorWithRed:0.221 green:0.643 blue:0.969 alpha:1.000];
    [chooseBgView addSubview:_viewB];
}

//直播信息列表
-(void)addVideoLive
{
    //视频信息列表
    _tableLive = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+50, kScreenWidth, kScreenHeight-64-50) style:UITableViewStylePlain];
    _tableLive.delegate = self;
    _tableLive.dataSource = self;
    _tableLive.bounces = YES;
    [_tableLive setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableLive setBackgroundColor:[UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000]];
    [self.view addSubview:_tableLive];
}

//集成刷新控件
-(void)setupRefresh
{
    NSString *refIdentifier = @"cellRrefresh";
    //注册cell
    [_tableLive registerClass:[UITableViewCell class] forCellReuseIdentifier:refIdentifier];
    
    //上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableLive addFooterWithTarget:self action:@selector(footerRereshing)];
    
    _tableLive.footerPullToRefreshText = @"上拉加载更多";
    _tableLive.footerReleaseToRefreshText = @"释放立即加载";
    _tableLive.footerRefreshingText = @"正在加载...";
}


//上拉加载的方法
- (void)footerRereshing
{
    int page = [_rep.strPageNo intValue]+1;
    SetUpSingleton *set = [SetUpSingleton sharedSetUp];
    int pageMax = 0;
    if ([_rep.strStyleID intValue] == 166) {
        pageMax = set.pageWeiShiNumber;
    }
    else{
        pageMax = set.pageDiFangNumber;
    }
    if (page > 0 && page <= pageMax)
    {
        _rep.strPageNo = [NSString stringWithFormat:@"%d",page];
        [Loading showLoadingWithView:self.view];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//执行耗时操作
            //获取直播信息
            _rep.flag = ++_rep.flag;
            _arrId = [DBDaoHelper selectLiveID:_rep.flag];
            //从数据库请求数据
            [self selectDBDAO:_arrId.count];
            dispatch_async(dispatch_get_main_queue(), ^{//主线程更新UI
                [Loading hiddonLoadingWithView:self.view];
                //2秒后刷新UI  刷新表格
                [_tableLive reloadData];
            });
        });
    }
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [_tableLive footerEndRefreshing];
}

//行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arrLive.count;
}

//列表每行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

//列表每行显示的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *liveIdentifier = @"cellLive";
    int row = (int)[indexPath row];
    
    //获取cell row ＝ 0 获取不到 进入创建cell
    LiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:liveIdentifier];
    if (cell == nil)
    {
        cell = [[LiveTableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:liveIdentifier];
        [cell setBackgroundColor:[UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    LiveInfo *live = [_arrLive objectAtIndex:row];
    cell.labTvName.text = live.strResTitle;
    if (live.strTitle.length == 0 || live.strNextTitle.length == 0) {
        cell.labNowTheatre.text = @"暂无信息";
        cell.labWillTheatre.text = @"暂无信息";
    }
    else{
        cell.labNowTheatre.text = live.strTitle;
        cell.labWillTheatre.text = live.strNextTitle;
    }

    if (![live.strThumbnail isKindOfClass:[NSNull class]] && live.strThumbnail.length > 0){//不是空字符串的
         [cell.img setImageWithURL:[NSURL URLWithString:live.strThumbnail] placeholderImage:[UIImage imageNamed:@"app_default.png"]];
    }
    else{//空串
        [cell.img setImage:[UIImage imageNamed:@"app_default.png"]];
    }
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LiveInfo *live = [_arrLive objectAtIndex:indexPath.row];
    _detail = [[DetailInfo alloc]init];
    //获取当前时间
    NSDate *datenow = [[NSDate alloc]init];
    _detail.dateTime = datenow;
    _detail.strResId = live.strResId;
    _detail.strThumbnail = live.strThumbnail;
    _detail.strTitle = live.strResTitle;
    _detail.strCategoryId = self.classInfo.strCategoryId;
    _detail.strResUrl = live.strPlayUrl;
    
    if (live.strPlayUrl.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:MyLocalizedString(@"alertinfo1") message:MyLocalizedString(@"alertinfo9") delegate:nil cancelButtonTitle:MyLocalizedString(@"sure") otherButtonTitles:nil];
        [alert show];
    }
    else{
        _strUrlWebView = live.strPlayUrl;
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [Loading showLoadingWithView:app.window];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//执行耗时操作
            //调用网址解析获取视频文件地址
            [self touShe:live.strPlayUrl];
            dispatch_async(dispatch_get_main_queue(), ^{//主线程更新UI
                [Loading hiddonLoadingWithView:app.window];
                if (_strRUrl.length == 0) {
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:MyLocalizedString(@"alertinfo1") message:MyLocalizedString(@"alertinfoa") delegate:self cancelButtonTitle:MyLocalizedString(@"cancel") otherButtonTitles:MyLocalizedString(@"alertinfob"),nil];
                    [alert show];
                }
                else{
                    if (_matchstickController.deviceScanner.devices.count > 0) {
                        //调用设备选择页面
                        [self addAction];
                    }
                    else{
                        //网页播放
                        [self webPlay];
                    }
                }
            });
        });
    }
}

//网页播放按钮的事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1){
        //网页播放
        [self webPlay];
    }
}

-(void)touShe:(NSString *)str_url{
    //用逗号分开，取第一个数据源
    NSArray *array;
    if (str_url != nil) {
        array = [str_url componentsSeparatedByString:@","];
    }
    NSString *firstUrl = @"";
    if (array && array.count > 0) {
        firstUrl = [array firstObject];
    }
    NSLog(@"___________________firstUrl:%@",firstUrl);
    //网址解析
    const LPCSTR url = [firstUrl cStringUsingEncoding:NSASCIIStringEncoding];
    [libaUrl URLTIsRunning];
    const int sourceId = 0;
    char realURL[1024*30];// = new char(1024*30);
    int len = 1024*30;
    const LPCSTR ua = "";
    const LPCSTR sourceKind = "";
    const LPCSTR spiderName = "";
    const LPCSTR videoParam = "";
    [libaUrl AnalysisRealUrlForAndroidMorefun: sourceId url:url realurl:realURL len:len ua:ua skind:sourceKind spiderName:spiderName videoParam:videoParam];
    _strRealUrlAll = [NSString stringWithUTF8String:realURL];
    if (_strRealUrlAll.length != 0){
        _urlDic = [NSJSONSerialization JSONObjectWithData: [_strRealUrlAll dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: nil];
        NSLog(@"____________________urlDic:%@",_urlDic);
        _arr1 = [_urlDic objectForKey:@"nd"];
        _arr2 = [_urlDic objectForKey:@"sd"];
        _arr3 = [_urlDic objectForKey:@"hd"];
        _strRUrl = @"";
        if(_arr1.count == 0){
            if (_arr2.count == 0) {
                if (_arr3.count != 0) {
                    _strRUrl = [_arr3 objectAtIndex:0];
                }
            }else{
                _strRUrl = [_arr2 objectAtIndex:0];
            }
        }
        else{
            _strRUrl = [_arr1 objectAtIndex:0];
        }
    }
}

//调用设备选择页面
-(void)addAction{
    _arrSheet = [[NSMutableArray alloc]init];
    if (_matchstickController.isConnected) {
        _cusAlterView.isConnect = YES;
    }
    else{
        _cusAlterView.isConnect = NO;
        for (int i = 0; i < _matchstickController.deviceScanner.devices.count; i++) {
            MSFKDevice *device = [_matchstickController.deviceScanner.devices objectAtIndex:i];
            [_arrSheet addObject:device.friendlyName];
        }
        _cusAlterView.arrCustom = _arrSheet;
    }
    //图标变化
    [_cusAlterView rightBtnImageChange];
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView animateWithDuration:0.25f animations:^{
        _cusAlterView.alpha = 1.0;
    }];
}

//投射按钮协议事件
-(void)customTouSheBtnAlterView:(AlertCustomView *)alter{
    [self touShePlay];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView animateWithDuration:0.25f animations:^{
        _cusAlterView.alpha = 0.0;
    }];
}

//网页播放和添加列表按钮协议事件
-(void)customWebORAddBtnAlterView:(AlertCustomView *)alter{
    if (_cusAlterView.isConnect == NO) {//网页播放
        [self webPlay];
        [_cusAlterView tableChange];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView animateWithDuration:0.25f animations:^{
            _cusAlterView.alpha = 0.0;
        }];
    }
    else{//添加队列
        BOOL result = [DBDaoHelper selectTouShe:_detail.strTitle];
        if (result == YES) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:MyLocalizedString(@"alertinfo1") message:MyLocalizedString(@"alertinfo8") delegate:nil cancelButtonTitle:MyLocalizedString(@"sure") otherButtonTitles:nil];
            [alert show];
        }
        else{
            SetUpSingleton *set = [SetUpSingleton sharedSetUp];
            set.strAddTouShe = @"YES";
            DetailInfo *dea = [[DetailInfo alloc]init];
            dea.strTitle = _detail.strTitle;
            dea.strRealUrl = _strRUrl;
            dea.strAllURL = _strRealUrlAll;
            //查询投射信息是否已经插入
//            if (![DBDaoHelper selectTouShe:dea.strTitle]) {
                //插入投射记录信息
                [DBDaoHelper insertTouShe:dea];
//            }
        }
        
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView animateWithDuration:0.25f animations:^{
            _cusAlterView.alpha = 0.0;
        }];
    }
}

//cell的点击协议
-(void)cellTouchAlterView:(AlertCustomView *)alter RowAtIndexPath:(NSIndexPath *)indexPath{
    SetUpSingleton *set = [SetUpSingleton sharedSetUp];
    NSMutableArray *deviceArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < _matchstickController.deviceScanner.devices.count; i++) {
        MSFKDevice *device = [_matchstickController.deviceScanner.devices objectAtIndex:i];
        // only show LAN IP.
        if (device.ipAddress == nil
            || [device.ipAddress isEqualToString:@"192.168.1.1"]
            || !([device.ipAddress hasPrefix:@"192"]
                 || [device.ipAddress hasPrefix:@"172"]
                 || [device.ipAddress hasPrefix:@"10"])) {
                //过滤掉的设备
            }
        else {
            [deviceArr addObject:device];
        }
    }
    MSFKDevice *device = [deviceArr objectAtIndex:indexPath.row];
    NSLog(@"Selecting device3:%@", device.friendlyName);
    [_matchstickController connectToDevice:device];
    NSString *str = [_arrSheet objectAtIndex:[indexPath row]];
    set.arrSheet = [[NSMutableArray alloc]init];
    [set.arrSheet addObject:str];
    
    _pushmat = YES;
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView animateWithDuration:0.25f animations:^{
        _cusAlterView.alpha = 0.0;
    }];
}

//点击事件的协议
-(void)tapRecognizerAlterView:(AlertCustomView *)alterView{
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView animateWithDuration:0.25f animations:^{
        [_cusAlterView tableChange];
        _cusAlterView.alpha = 0.0;
    }];
}

- (void)didConnectToDevice:(MSFKDevice *)device {
    lastKnownPlaybackTime = [self.moviePlayer currentPlaybackTime];
    [self.moviePlayer stop];
    if (_pushmat == YES) {
        _pushmat = NO;
        [self touShePlay];
    }
}

-(void)touShePlay{
    SetUpSingleton *set = [SetUpSingleton sharedSetUp];
    //隐藏浮动的按钮
    set.strHidden = @"YES";
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BtnSetHidden" object:nil userInfo:nil];
    UIButton *matchstickButton = (UIButton *) _matchstickController.matchstickBarButton.customView;
    [matchstickButton setImage:[UIImage imageNamed:@"playing.png"] forState:UIControlStateNormal];
//    NSLog(@"_____________playing.png");
    
    set.strAddTouShe = @"NO";
    set.count = 0;
    DetailInfo *detail = [[DetailInfo alloc]init];
    detail.strTitle = _detail.strTitle;
    detail.strRealUrl = _strRUrl;
    detail.strAllURL = _strRealUrlAll;
    detail.strThumbnail = _detail.strThumbnail;
    //查询投射信息是否已经插入
    if (![DBDaoHelper selectTouShe:detail.strTitle]) {
        detail.strPlayId = _detail.strPlayId;
        //插入投射记录信息
        [DBDaoHelper insertTouShe:detail];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateHistoryPlay" object:nil userInfo:nil];
    //投射播放
    MatchStickViewController *mat = [[MatchStickViewController alloc]initWithRealUrl:_strRUrl];
    mat.mediaToPlay = _detail;
    set._titleString = _detail.strTitle;
//    NSLog(@"_______________%@",[SetUpSingleton sharedSetUp]._titleString);
    mat.strAllRealUrl = _strRealUrlAll;
    [self presentViewController:mat animated:YES completion:^{
    }];
}


//返回前一页
-(void)clickRetun
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

//频道选择按钮事件
-(void)clickChoose:(UIButton *)sender
{
    _rep.strPageNo = @"1";
    _rep.portID = 1;
    if (sender.tag == 20)
    {
        [UIView animateWithDuration:0.2f animations:^{
            _viewB.frame = CGRectMake(15, 47, 50, 3);
        }];
        _rep.strStyleID = @"166";//卫视  167地方台
    }
    else
    {
        [UIView animateWithDuration:0.2f animations:^{
            _viewB.frame = CGRectMake(15+kScreenWidth/4, 47, 50, 3);
        }];
        _rep.strStyleID = @"167";//卫视  167地方台
        _rep.flag = 10;
        _rep.flagPage = 10011111;
    }
    
    [Loading showLoadingWithView:self.view];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//执行耗时操作
        SetUpSingleton *setUp = [SetUpSingleton sharedSetUp];
        if (setUp.firstDiFangID == YES) {//如果当天第一次进入直接更新
            [NetWorkingHelper getLiveInfoWithRequestParameter:_rep];
            _rep.flagPage = 10000;
            for (int i = 0; i < setUp.pageDiFangNumber; i++) {
                _rep.portID = 1;
                _rep.flag = ++_rep.flag;
                _rep.strPageNo = [NSString stringWithFormat:@"%d",i+1];
                //请求直播台的id信息 并存入数据库
                _arrId = [NetWorkingHelper getLiveInfoWithRequestParameter:_rep];

                setUp.firstDiFangID = NO;
            }
        }

        if (sender.tag == 20){
            _rep.flag = 1;
        }
        else{
            _rep.flag = 11;
        }
        //查询直播的ID
        _arrId = [DBDaoHelper selectLiveID:_rep.flag];
        if (setUp.firstDiFangEPG == YES) {
            [DBDaoHelper deleteAllEPG];//删除所有EPG信息
            //获取详细的EPG信息 并存入数据库
            [NetWorkingHelper getDetailEPGInfoWith:_rep ArrLive:_arrId];
            setUp.firstDiFangEPG = NO;
        }
        _rep.strPageNo = @"1";
        
        [_arrLive removeAllObjects];
        //查询详细的EPG信息
        [self selectDBDAO:(int)_arrId.count];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //主线程更新UI
            [Loading hiddonLoadingWithView:self.view];
            [_tableLive reloadData];
        });
    });
}

//网页播放视频
-(void)webPlay
{
    //网页播放视频
    WebviewViewController *we = [[WebviewViewController alloc]initWithHtmlUrl:_strUrlWebView];
    [self presentViewController:we animated:YES completion:^{
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
